package com.agrm.user.controller;

import com.agrm.model.common.dtos.PageRequestDto;
import com.agrm.model.common.dtos.PageResponseResult;
import com.agrm.model.common.dtos.ResponseResult;
import com.agrm.model.user.dto.UserQuery;
import com.agrm.model.user.dto.UserSafeDto;
import com.agrm.model.user.pojo.User;
import com.agrm.user.service.UserService;
import com.agrm.utils.JwtUtil;
import com.agrm.utils.WebAppUtils;
import com.alibaba.nacos.api.model.v2.Result;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.checkerframework.checker.units.qual.A;
import org.jasypt.util.password.StrongPasswordEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("api/v1/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Value("${jwt.secretKey}")
    private String secretKey;
    private final StrongPasswordEncryptor pe = new StrongPasswordEncryptor();


    private final RedisTemplate<String, Object> redisTemplate;

    public UserController(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }


    /**
     * 用户登录接口
     *
     * @param user 包含用户登录信息的请求体，包含用户名、密码和验证码信息
     * @return 返回ResponseResult，包含登录结果或错误信息
     */
    @PostMapping("/login")
    public ResponseResult login(@RequestBody User user,
                                HttpServletRequest req,
                                HttpServletResponse resp) {
        // 从Redis中获取并删除验证码，captchaId是验证码的唯一标识
        String captcha = (String) redisTemplate.opsForValue().getAndDelete("captcha-" + user.getCaptchaId());
        // 验证码校验，如果验证码不匹配则返回错误信息
        if (!user.getCaptcha().equals(captcha)) {
            return ResponseResult.errorResult(-1, "验证码错误");
        }

        // 根据用户名查询用户信息
        User byUsername = userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername()));

        // 判断用户是否存在，不存在则返回错误信息
        if (byUsername == null) {
            return ResponseResult.errorResult(-1, "用户不存在");
        }


        // 校验密码，使用pe工具类的checkPassword方法进行密码验证
        if (!pe.checkPassword(user.getPassword(), byUsername.getPassword())) {
            return ResponseResult.errorResult(-1, "密码错误");
        }
        String jwtId = UUID.randomUUID().toString();
        String jwt = JwtUtil.encode(jwtId, byUsername, 30, secretKey);
        resp.setHeader("x-auth-token", jwt);//将jwt设置到响应头中
        //将用户信息存储到redis缓冲
        redisTemplate.opsForValue().set(jwtId, byUsername, Duration.ofMinutes(30));
        //登录成功
        byUsername.setLastLoginTime(LocalDateTime.now());
        byUsername.setLoginTimes(byUsername.getLoginTimes() + 1);
        byUsername.setPassword(null);//不修改密码
        this.userService.updateById(byUsername);

        // 生成JWT令牌，包含用户ID、用户名等信息，设置30分钟过期时间
        return ResponseResult.okResult(jwt);
    }


    /**
     * 根据id查询用户
     *
     * @param id 用户id
     * @return 用户信息
     */
    @GetMapping("/get")
    public ResponseResult getById(Integer id) {
        return ResponseResult.okResult(userService.getById(id));
    }


    /**
     * 查询所有用户
     *
     * @return 所有用户信息
     */
    @GetMapping("/getAll")
    public ResponseResult getAll() {
        return ResponseResult.okResult(userService.list());
    }


    /**
     * 分页查询用户
     *
     * @param page  分页参数
     * @param query 查询参数
     * @return 用户信息
     */
    @GetMapping("/list")
    public PageResponseResult list(PageRequestDto page, UserQuery query) {
        IPage<User> pages = userService.pageQueryList(page, query);
        PageResponseResult pageResponseResult = new PageResponseResult(page.getPage(), page.getSize(), (int) pages.getTotal());
        pageResponseResult.setData(pages.getRecords());

        return pageResponseResult;
    }


    /**
     * 添加用户
     *
     * @param user
     * @return
     */
    @PostMapping("/add")
    public ResponseResult add(@RequestBody User user) {
        return ResponseResult.okResult(userService.save(user));
    }


    /**
     * 修改用户
     *
     * @param user
     * @return
     */
    @PutMapping("/update")
    public ResponseResult update(@RequestBody User user) {
        return ResponseResult.okResult(userService.updateById(user));
    }


    /**
     * 删除用户
     *
     * @param id
     * @return
     */
    @DeleteMapping("/delete")
    public ResponseResult delete(@RequestBody Integer id) {
        return ResponseResult.okResult(userService.removeById(id));
    }

}
